import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/routers/routers.dart';
import 'package:taonile/utils/double_utils.dart';

import '../config/config.dart';
import '../entity/product_detail_entity.dart';
import '../entity/receipt_address_entity.dart';
import '../entity/shopping_car_list_entity.dart';
import '../http/api.dart';
import '../utils/common_utils.dart';
import '../utils/event_msg.dart';
import '../utils/singleton_manager.dart';
import '../views/number_controller_widget.dart';

///
/// 订单确认页面
///
class OrderConfirmPage extends StatefulWidget {
  var buyNum = '1';
  var productName = '';
  var storeName = '';
  var storeId = '';
  var storeLogo = '';
  var tag = '1';
  var isCar = '0';
  var amount = '0';
  var expressMoney = '0';

  OrderConfirmPage(
      {Key? key,
      this.buyNum = "1",
      this.productName = '',
      this.storeName = '',
      this.storeId = '',
      this.storeLogo = '',
      this.isCar = '0',
      this.tag = '1',
      this.amount = '0',
      this.expressMoney = '0'})
      : super(key: key);

  @override
  State<OrderConfirmPage> createState() => _OrderConfirmPageState();
}

class _OrderConfirmPageState extends State<OrderConfirmPage> {
  ReceiptAddressData receiptAddressData = ReceiptAddressData();
  var remark = '';

  //直接购买相关的
  var newBuyNum = "1";
  var spuCurrent = '';
  var totalAmount = '0.00';
  ProductDetailDataSku currentSku = ProductDetailDataSku();

  //购物车下单相关的
  List<ShoppingCarListData> datas = [];
  var listHeight = 245.w;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getReceipts();

    if (widget.isCar == '0') {
      newBuyNum = widget.buyNum;
      currentSku = SingletonManager.instance.currentSKu;
      StringBuffer sb = StringBuffer();
      for (int i = 0; i < currentSku.specVal.length; i++) {
        sb.write(currentSku.specVal[i]);
        if (i != currentSku.specVal.length - 1) {
          sb.write('/');
        }
      }
      spuCurrent = sb.toString();
      getTotalAmount();
    } else {
      datas = SingletonManager.instance.currentCarConfirm;
      totalAmount = widget.amount;
      getListHeight();
    }
  }

  getListHeight() {
    double hei = 0.w;
    for (var item in datas) {
      hei += 80.w;
      hei += 20;
      for (var item2 in item.goodsData) {
        hei += 145.w;
      }
    }
    listHeight = hei;
  }

  getReceipts() async {
    dynamic result = await Api.receiptList();
    ReceiptAddressEntity entity = ReceiptAddressEntity.fromJson(result);
    setState(() {
      if (entity.data.isNotEmpty) {
        receiptAddressData = entity.data[0];
      }
    });
  }

  getTotalAmount() async {
    if (widget.tag == '1') {
      dynamic result = await Api.confirmOrder({
        "payload": {currentSku.id: newBuyNum}
      });
      var jsonResult = jsonDecode(jsonEncode(result));
      setState(() {
        List<dynamic> amountObj = jsonResult['data'];
        dynamic obj = amountObj[0];
        // LogUtil.v(obj.toString(), tag: '总价格1=');
        Map<dynamic, dynamic> amountNew = Map.from(obj);
        // LogUtil.v(amountNew['money'], tag: '总价格2=');
        var money = amountNew['money'];
        var company = amountNew['company'];
        var money1 = amountNew['money1'];
        var company1 = amountNew['company1'];

        totalAmount = CommonUtils.formatAmountUnit(money, company, money1, company1);
      });
    } else {
      setState(() {
        double amount = double.parse(currentSku.price) * double.parse(newBuyNum);
        String all = DoubleUtils.formartNum(amount + double.parse(widget.expressMoney), 2);
        totalAmount = '$all金券';
      });
    }
  }

  addOreder() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (receiptAddressData.id.isEmpty) {
      EasyLoading.showToast("请添加收货地址");
      return;
    }
    dynamic result = await Api.createOrder({
      "payload": [
        {"sku_id": currentSku.id, "buy_num": newBuyNum}
      ],
      "receipt_id": receiptAddressData.id,
      "remark": remark.isEmpty ? '无' : remark,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String orderNo = jsonResult['data']['order_no'];
      print(orderNo);
      Routes.navigateTo(context, Routes.orderCashier,
              params: {'amount': totalAmount, 'orderNo': orderNo, "skuId": currentSku.id})
          .then((value) {
        Routes.router.pop(context);
        Routes.navigateTo(context, Routes.orderDetail, params: {'orderNo': orderNo});
      });
    }
  }

  addOrederNew() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (receiptAddressData.id.isEmpty) {
      EasyLoading.showToast("请添加收货地址");
      return;
    }
    dynamic result = await Api.createOrderNew({
      "store_id": widget.storeId,
      "sku_id": currentSku.id,
      "buy_num": newBuyNum,
      "receipt_id": receiptAddressData.id,
      "remark": remark.isEmpty ? '无' : remark,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String orderNo = jsonResult['data'];
      print(orderNo);
      Routes.navigateTo(context, Routes.orderCashier, params: {
        'amount': totalAmount,
        'orderNo': orderNo,
        'payApiType': '2',
      }).then((value) {
        Routes.router.pop(context);
        Routes.navigateTo(context, Routes.orderDetail, params: {'orderNo': orderNo});
      });
    }
  }

  addOrederForCar() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (receiptAddressData.id.isEmpty) {
      EasyLoading.showToast("请添加收货地址");
      return;
    }
    dynamic result = await Api.createCarOrderNew({
      "cart_id": getCheckAmount(),
      "receipt_id": receiptAddressData.id,
      "remark": remark.isEmpty ? '无' : remark,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String orderNo = jsonResult['data'];
      print(orderNo);

      int index = totalAmount.indexOf('(');
      String amount = totalAmount.substring(0, index);
      Routes.navigateTo(context, Routes.orderCashier, params: {
        'amount': amount,
        'orderNo': orderNo,
        'payApiType': '2',
      }).then((value) {
        Routes.router.pop(context);
        SingletonManager.instance.eventBus.fire(ShoppingCarUp());
        Routes.navigateTo(context, Routes.orderIndex, params: {'currentIndex': '0'});
      });
    }
  }

  //计算所有已选中的商品价格合计
  String getCheckAmount() {
    String str = '';
    StringBuffer ids = StringBuffer();
    for (var item in datas) {
      for (var item2 in item.goodsData) {
        ids.write(item2.businessCartId);
        ids.write(',');
      }
    }
    if (ids.length > 1) {
      str = ids.toString().substring(0, ids.length - 1);
    }
    return str;
  }

  getListItem(bool isCar, int index) {
    return Container(
      //商品信息
      margin: EdgeInsets.only(top: 20.w, left: 20.w, right: 20.w),
      decoration: BoxDecoration(
        color: Config.colorWhite,
        borderRadius: BorderRadius.circular(10.w),
      ),
      width: double.infinity,
      padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 0.w),
      child: Column(
        children: [
          Container(
            height: 80.w,
            decoration: BoxDecoration(
              color: Colors.transparent,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CachedNetworkImage(
                  imageUrl: isCar ? datas[index].storeLogo : widget.storeLogo,
                  fit: BoxFit.fill,
                  width: 32.w,
                  height: 32.w,
                  errorWidget: (context, url, error) {
                    return Image.asset(
                      'assets/images/bg_default_400.png',
                      width: 32.w,
                      height: 32.w,
                      fit: BoxFit.fill,
                    );
                  },
                ),
                Padding(
                  padding: EdgeInsets.only(left: 10.w),
                ),
                Expanded(
                  child: Text(
                    isCar ? datas[index].storeBaseName : widget.storeName,
                    style: TextStyle(fontSize: 24.sp),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: double.infinity,
            // margin: EdgeInsets.only(top: 10.w),
            height: isCar ? 145.w * datas[index].goodsData.length : 145,
            child: ListView.builder(
              physics: const NeverScrollableScrollPhysics(),
              itemCount: isCar ? datas[index].goodsData.length : 1,
              scrollDirection: Axis.vertical,
              itemBuilder: (BuildContext context, int index2) {
                return getListItem2(isCar, index, index2);
              },
            ),
          ),
        ],
      ),
    );
  }

  getListItem2(bool isCar, int index, int index2) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 20.w),
      height: 145.w,
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Config.colorDivider, width: 1.w)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: EdgeInsets.only(right: 20.w),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: CachedNetworkImage(
                imageUrl: isCar ? datas[index].goodsData[index2].imgPath : currentSku.imgPath,
                fit: BoxFit.fill,
                width: 100.w,
                height: 100.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: 100.w,
                    height: 100.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 540.w,
                child: Text(
                  isCar ? datas[index].goodsData[index2].shopGoodsName : widget.productName,
                  softWrap: false,
                  style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                ),
              ),
              Container(
                width: 540.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      spuCurrent,
                      softWrap: true,
                      style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                    ),
                    Text(
                      "X${isCar ? datas[index].goodsData[index2].num : newBuyNum}",
                      softWrap: true,
                      style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 9.w),
              ),
              Text(
                isCar
                    ? '${datas[index].goodsData[index2].price}金券'
                    : CommonUtils.formatAmountUnit(currentSku.money, currentSku.company,
                        currentSku.money1, currentSku.company1),
                softWrap: true,
                style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('确认订单'),
        centerTitle: true,
      ),
      bottomNavigationBar: Container(
        decoration: const BoxDecoration(color: Config.colorBg),
        height: 100.w,
        width: 750.w,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('合计：', style: TextStyle(fontSize: 26.sp, color: Config.colorText1)),
                  Text(totalAmount, style: TextStyle(fontSize: 26.sp, color: Colors.redAccent)),
                ],
              ),
            ),
            Container(
              width: 200.w,
              margin: EdgeInsets.only(left: 25.w),
              child: ElevatedButton(
                clipBehavior: Clip.antiAlias,
                onPressed: () {
                  if (widget.isCar == '1') {
                    addOrederForCar();
                  } else {
                    if (widget.tag == '1') {
                      addOreder();
                    } else {
                      addOrederNew();
                    }
                  }
                },
                style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                child: const Text('立即购买'),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        width: double.infinity,
        color: Config.colorBg2,
        height: double.infinity,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                    //收货信息
                    margin: EdgeInsets.only(top: 20.w, left: 20.w, right: 20.w),
                    decoration: BoxDecoration(
                      color: Config.colorWhite,
                      borderRadius: BorderRadius.circular(10.w),
                    ),
                    width: double.infinity,
                    height: 132.w,
                    padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 22.w),
                    child: receiptAddressData.id.isNotEmpty
                        ? InkWell(
                            onTap: () {
                              Routes.navigateTo(context, Routes.mineAddressChoose).then((value) {
                                setState(() {
                                  receiptAddressData = value;
                                });
                              });
                            },
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "收货人：${receiptAddressData.username}",
                                      style: TextStyle(fontSize: 24.sp),
                                    ),
                                    Text(
                                      receiptAddressData.mobile,
                                      style: TextStyle(fontSize: 24.sp),
                                    ),
                                  ],
                                ),
                                Padding(
                                  padding: EdgeInsets.only(top: 20.w),
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    // Icon(
                                    //   Icons.location_on_outlined,
                                    //   size: 32.w,
                                    //   color: Config.colorText1,
                                    // ),
                                    Expanded(
                                      child: Text(
                                        "收货地址：${receiptAddressData.provinceName}${receiptAddressData.cityName}${receiptAddressData.areaName}${receiptAddressData.detail}",
                                        softWrap: false,
                                        style: TextStyle(fontSize: 23.sp),
                                      ),
                                    ),
                                    Icon(
                                      Icons.arrow_forward_ios,
                                      size: 25.w,
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          )
                        : InkWell(
                            onTap: () {
                              Routes.navigateTo(context, Routes.mineAddressChoose).then((value) {
                                setState(() {
                                  receiptAddressData = value;
                                });
                              });
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Icon(
                                  Icons.location_on_outlined,
                                  size: 32.w,
                                  color: Config.colorText1,
                                ),
                                Expanded(
                                  child: Text(
                                    "点击添加收货地址",
                                    style: TextStyle(fontSize: 24.sp),
                                  ),
                                ),
                                Icon(
                                  Icons.arrow_forward_ios,
                                  size: 25.w,
                                ),
                              ],
                            ),
                          ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 147.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(12.w),
                        bottomRight: Radius.circular(12.w),
                      ),
                      child: Image.asset(
                        "assets/images/ic_reciver_divider.png",
                        fit: BoxFit.fill,
                        width: double.infinity,
                        height: 6.w,
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                height: listHeight,
                child: ListView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: datas.isEmpty ? 1 : datas.length,
                  scrollDirection: Axis.vertical,
                  itemBuilder: (BuildContext context, int index) {
                    return getListItem(datas.isEmpty ? false : true, index);
                  },
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 20.w, left: 20.w, right: 20.w, bottom: 25.w),
                decoration: BoxDecoration(
                  color: Config.colorWhite,
                  borderRadius: BorderRadius.circular(10.w),
                ),
                child: Column(
                  children: [
                    Visibility(
                      visible: widget.isCar == '0',
                      child: Container(
                        width: double.infinity,
                        padding: EdgeInsets.all(25.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              "购买数量",
                              style: TextStyle(fontSize: 24.sp),
                            ),
                            NumberControllerWidget(
                              numText: newBuyNum,
                              addValueChanged: (num) {
                                setState(() {
                                  newBuyNum = num.toString();
                                  getTotalAmount();
                                });
                              },
                              removeValueChanged: (num) {
                                setState(() {
                                  newBuyNum = num.toString();
                                  getTotalAmount();
                                });
                              },
                              updateValueChanged: (num) {},
                            )
                          ],
                        ),
                      ),
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 2.w,
                      thickness: 2.w,
                    ),
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(25.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "物流费用",
                            style: TextStyle(fontSize: 24.sp),
                          ),
                          Text(
                            '${widget.expressMoney}金券',
                            style: TextStyle(fontSize: 24.sp),
                          ),
                        ],
                      ),
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 2.w,
                      thickness: 2.w,
                    ),
                    Container(
                      margin: EdgeInsets.only(bottom: 10.w),
                      width: double.infinity,
                      padding: EdgeInsets.all(25.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            "订单备注",
                            style: TextStyle(fontSize: 24.sp),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 530.w,
                            height: 36.w,
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              // maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  remark = value;
                                });
                              },
                              style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                              decoration: const InputDecoration.collapsed(
                                hintText: '选填，对本次交易得说明',
                                hintStyle: TextStyle(color: Config.colorText3),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
